package com.study.forumsystemproject.controller;

import com.study.forumsystemproject.common.MessageState;
import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.common.ResultCode;
import com.study.forumsystemproject.exception.ApplicationException;
import com.study.forumsystemproject.model.Message;
import com.study.forumsystemproject.model.User;
import com.study.forumsystemproject.service.IMessageService;
import com.study.forumsystemproject.service.IUserService;
import com.study.forumsystemproject.service.impl.MessageImpl;
import com.study.forumsystemproject.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * program: forum-system-project
 * <p>
 * description: 私信控制层
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-19 23:08
 **/
@RequestMapping("/message")
@RestController
@Slf4j
@Tag(name = "私信类测试API")
public class MessageController {

    @Autowired
    private IMessageService messageService;
    @Autowired
    private IUserService userService;
    @Operation(summary = "发送私信的API")
    @PostMapping("/send")
    public Result<Boolean> sendMessage(HttpServletRequest request, @RequestBody Message message) {
        //进行参数校验
        if (message == null || message.getContent() == null
                 || message.getReceiveUserId() == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return Result.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //获取发送者id
        Long userId = ((Number) JwtUtil.getValue(request,"UserId")).longValue();
        //校验发送者的状态,以及不能发送给自己
        User userInfo = userService.getUserInfo(userId);
        if (userInfo == null || userInfo.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(userInfo.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        //不能发送给自己
        if(Objects.equals(userInfo.getId(), message.getReceiveUserId())) {
            return Result.fail("禁止发送私信给自己");
        }
        //判断接收者用户是否存在
        User receiveUser = userService.getUserInfo(message.getReceiveUserId());
        if (receiveUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        message.setPostUserId(userId);
        messageService.sendMessage(message);
        return Result.success(true);
    }
    @Operation(summary = "获取未读信息的API")
    @GetMapping("/getNotRedMessage")
    public Result<Integer> getNotRedMessage(HttpServletRequest request) {
        Long userId = ((Number) JwtUtil.getValue(request,"UserId")).longValue();
        User userInfo = userService.getUserInfo(userId);
        if (userInfo == null ) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        Integer i = messageService.selectNotRedByReceiveUserId(userId);
        if (i == null) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            return Result.fail(ResultCode.ERROR_SERVICES);
        }
        return Result.success(i);
    }
    @Operation(summary = "获取私信列表的API")
    @GetMapping("/getList")
    public Result<List<Message>> getMessageList(HttpServletRequest request) {
        Long userId = ((Number) JwtUtil.getValue(request,"UserId")).longValue();
        List<Message> messages = messageService.selectRedByReceiveUserId(userId);
        return Result.success(messages);
    }
    @Operation(summary = "设置为已读的API")
    @PostMapping("/readMessage")
    public Result<Boolean> readMessage(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return Result.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        messageService.updateRedById(id, MessageState.READ);
        return Result.success(true);
    }

    @Operation(summary = "设置为已读的API")
    @PostMapping("/reply")
    public Result<Boolean> replyMessage(HttpServletRequest request, @NotNull Long repliedId, @NotNull String content) {
        Long userId = ((Number) JwtUtil.getValue(request,"UserId")).longValue();
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //校验发送者和接收者是否为同一个人
        if(userId == message.getPostUserId()){
          return Result.fail("禁止向自己私信");
        }
        Message replyMessage = new Message();
        replyMessage.setId(repliedId);
        replyMessage.setContent(content);
        messageService.reply(replyMessage);
        return Result.success(true);
    }
}
